import {
  CanActivate,
  ExecutionContext,
  Injectable,
  Inject,
  UnauthorizedException,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { Reflector } from '@nestjs/core';
import { Request } from 'express';

@Injectable()
export class PermissionGuard implements CanActivate {
  @Inject(Reflector)
  private readonly reflector: Reflector;
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const requirePermissions = this.reflector.getAllAndOverride<string[]>(
      'require-permission',
      [context.getHandler(), context.getClass()],
    );
    // 如果没有设置requirePermissions，不需要权限，直接放行
    if (!requirePermissions) {
      return true;
    }
    const request: Request = context.switchToHttp().getRequest();
    const user = request.user;
    for (const permission of requirePermissions) {
      if (!user.permissions.includes(permission)) {
        throw new UnauthorizedException(`没有此接口权限`);
      }
    }
    return true;
  }
}
